import { get, set } from 'lodash-es'
import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useSessionStoreWithOut } from '@/store/modules/session'
// import { useDictStoreWithOut } from '@/store/modules/dict'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { getUserInfoApi } from '@/api/user'

const permissionStore = usePermissionStoreWithOut()

const appStore = useAppStoreWithOut()
const sessionStore = useSessionStoreWithOut()

// const dictStore = useDictStoreWithOut()

const { wsCache } = useCache()

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const whiteList = ['/login'] // 不重定向白名单

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (wsCache.get(appStore.getUserInfo)) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (permissionStore.getIsAddRouters) {
        // 动态路由已添加
        next()
        return
      }

      const res = await getUserInfoApi()
      const data = get(res, 'data')
      if (data?.routers && Array.isArray(data.routers)) {
        sessionStore.setHotels(data.hotels)
        sessionStore.setPermissions(data.permissions)
        sessionStore.setLoginName(data.login_name)
        sessionStore.setHotelId(data.hotel_id)
        sessionStore.setUserId(data.user_id)
        sessionStore.setUserType(data.user_type)
        // console.log(data.app_parameters)
        if (Array.isArray(data.app_parameters)) {
          const parameters = {
            FREEZE_ON_PASSWORD_ERROR: '',
            TRANSACTION_PASSWORD_REQUIRED: ''
          }

          for (const para of data.app_parameters) {
            set(parameters, para.app_parameter_name_id, para.app_parameter_value)
          }

          sessionStore.setParameters(parameters)
        }
        wsCache.set('token', data.token)

        await permissionStore.generateRoutes(data.routers as AppCustomRouteRecordRaw[])

        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
        })
        const redirectPath = from.query.redirect || to.path
        const redirect = decodeURIComponent(redirectPath as string)
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
        permissionStore.setIsAddRouters(true)
        next(nextData)
      } else {
        next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
